App({
  data: {
    deviceId: ""
  },
  globalData: {
    length: 0,
    orders: [],
    userStepsInfo: null,
    userInfo: null,
    runData: null,
    target: null,
    user: null,
    todayRun: null,
    authUser: false,
    authRun: false,
    auth: false,
    threeSession: null,
    isSearchOrder: false,
    createUser: false,
    isHide: false,
    domain: 'https://xcx.yuanhuatek.com/wechat/',
    url: 'https://xcx.yuanhuatek.com/',
    // domain: 'http://localhost:8080/wechat/',
    // url: 'http://localhost:8080/',
  },
  onShow: function () {
    if (this.globalData.isHide) {
      this.globalData.isHide = false;

    }
  },
  onHide: function () {
    this.globalData.isHide = true;
    this.globalData.length = 0;
  },
  onLaunch: function () {
    var self = this;
    this.globalData.isSearchOrder = false;
    setInterval(self.checkSession, 1000 * 30);
  },
  checkSession: function (callback) {
    var self = this;
    wx.checkSession({
      success: function () {
      },
      fail: function () {
        self.secLogin(callback); //重新登录
      }
    });
  },
  toAuth: function (userInfos) {
    var self = this;
    //授权
    if (userInfos != null && userInfos!=undefined){
      self.globalData.authUser = true;
    }
    self.globalData.userInfo = userInfos;
    wx.authorize({
      "scope": "scope.werun",
      "success": function (data) {
        self.globalData.authRun = true;
        wx.authorize({
          "scope": "scope.userLocation",
          "success": function (data) {
            //     self.globalData.authLocation = true;
            self.globalData.auth = true;
            wx.showLoading({
              title: '加载中',
            });
            self.login();
          },
          "fail": function (data) {
            wx.hideLoading();
            self.globalData.authLocation = false;
            wx.showToast({
              title: '请允许获取相关信息',
            });
          }
        });
      },
      "fail": function (data) {
        wx.hideLoading();
        self.globalData.authRun = false;
        wx.showToast({
          title: '请允许获取相关信息',
        });
      }
    });
  },
  login: function () {
    var self = this;
    // 登录
    wx.login({
      success: res => {
        if (res.code) {
          //发起网络请求
          wx.request({
            url: self.globalData.domain + 'user/login?code=' + res.code,
            dataType: 'json',
            success: function (threeSession) {
              if (threeSession.data == "fail") {
                return;
              }
              wx.setStorageSync('threeSession', threeSession.data);

              self.globalData.threeSession = threeSession.data;
              if (self.mineAuthReadyCallback) {
                self.mineAuthReadyCallback("ok");
              }
              if (self.countAuthReadyCallback) {
                self.countAuthReadyCallback("ok");
              }
              if (self.healthAuthReadyCallback) {
                self.healthAuthReadyCallback("ok");
              }
              if (self.stepAuthReadyCallback) {
                self.stepAuthReadyCallback("ok");
              }
              self.auth(threeSession.data);
            },
            fail: function (res) {
              wx.hideLoading();
            }
          })
        }
      }
    });
  },
  secLogin: function (callback) {
    var self = this;
    // 登录
    wx.login({
      success: res => {
        if (res.code) {
          //发起网络请求
          wx.request({
            url: self.globalData.domain + 'user/login?code=' + res.code,
            dataType: 'json',
            success: function (threeSession) {
              if (threeSession.data == "fail") {
                return;
              }
              wx.setStorageSync('threeSession', threeSession.data);
              self.globalData.threeSession = threeSession.data;
              if (callback) {
                callback();
              }
            },
            fail: function (res) {
              wx.hideLoading();
            }
          })
        } else {
        }
      }
    });
  },
  get3Session: function (callback) {
    var data = wx.getStorageSync('threeSession');
    if (data == null || data == undefined || data == 'undefined' || data == '') {
      this.toAuth();
    }
    return wx.getStorageSync('threeSession');
  },
  auth: function (threeSession) {
    // 获取用户信息
    var settings = null;
    var self = this;
    wx.getSetting({
      success: res => {
        settings = res;
        if (settings.authSetting['scope.userInfo']) {
          // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
          wx.request({
            url: this.globalData.domain + 'user/createUser',
            data: {
              threeSession: threeSession,
              touxiang: self.globalData.userInfo.avatarUrl,
              nickName: self.globalData.userInfo.nickName,
              gender: self.globalData.userInfo.gender
            },
            dataType: 'json',
            success: function (data) {
              if (data.data.gender != null && data.data.gender != 0) {
                self.globalData.userInfo.gender = data.data.gender;
              }
              // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
              // 所以此处加入 callback 以防止这种情况
              if (self.userInfoReadyCallback) {
                self.userInfoReadyCallback(self.globalData);
              }
              //微信运动
              if (settings.authSetting['scope.werun']) {
                wx.getWeRunData({
                  success: res => {
                    const encryptedData = res.encryptedData;
                    const iv = res.iv;
                    // 可以将 res 发送给后台解码出 unionId
                    wx.request({
                      url: self.globalData.domain + 'user/run?threeSession=' + threeSession + '&res=' + res,
                      data: {
                        res
                      },
                      dataType: 'json',
                      success: function (data) {
                        self.globalData.createUser = true;
                        wx.hideLoading();
                        self.globalData.runData = data;
                        if (self.runDataReadyCallback) {
                          self.runDataReadyCallback(res)
                        }
                        if (self.loadTarget) {
                          self.loadTarget();
                        }
                        self.getTarget(threeSession);
                        if (self.globalData.createUser && self.globalData.length == 0) {
                          self.getOrders(threeSession, 0, true);
                        }
                        if (settings.authSetting['scope.userLocation']) {
                          wx.getLocation({
                            type: 'wgs84',
                            success: function (location) {
                              wx.request({
                                url: self.globalData.domain + 'location/save?threeSession=' + threeSession,
                                data: location
                              })
                            }
                          })
                        }
                      },
                      fail: function (res) {
                        console.log("scope.werun error : " + res);
                      }
                    })
                  }
                });
              }
            },
            fail: function (data) {
              wx.hideLoading();
            }
          });
        } else {
          wx.hideLoading();
          wx.showToast({
            title: '请允许获取用户基本信息',
          })
        }
      }
    });
  },
  getTarget: function (threeSession) {
    var self = this;
    wx.request({
      url: self.globalData.domain + 'user/target?threeSession=' + threeSession,
      dataType: 'json',
      success: function (data) {
        if (data.data == '') {
          return;
        }
        self.globalData.target = data.data;
        if (self.targetReadyCallback) {
          self.targetReadyCallback(data)
        }
        self.getUser(threeSession);
      },
      fail: function (res) {
        wx.hideLoading();
      }
    })
  },
  getUser: function (threeSession) {
    var self = this;
    wx.request({
      url: self.globalData.domain + 'user/mine?threeSession=' + threeSession,
      dataType: 'json',
      success: function (data) {
        if (data.data.user == '') {
          return;
        }
        self.globalData.user = data.data.user;
        if (self.userReadyCallback) {
          self.userReadyCallback(data)
        }
        self.getUserStepsInfo(threeSession);
        return data.data.user;
      },
      fail: function (res) {
        wx.hideLoading();
      }
    })
  },
  getUserStepsInfo: function (threeSession) {
    var self = this;
    wx.request({
      url: self.globalData.domain + 'step/userStepsInfo?threeSession=' + threeSession,
      dataType: 'json',
      success: function (data) {
        if (data.data == '' || data.data == null) {
          return;
        }
        self.globalData.userStepsInfo = data.data;
        if (self.userStepInfoReadyCallback) {
          self.userStepInfoReadyCallback(data)
        }

      },
      fail: function (res) {
        wx.hideLoading();
      }
    })
  },
  getOrders: function (threeSession, next, isFirst) {
    if (!this.globalData.isSearchOrder) {
      this.globalData.isSearchOrder = true
    } else {
      wx.hideLoading();
      return;
    }
    var self = this;
    wx.showLoading({
      title: '请稍等',
    })
    wx.request({
      url: self.globalData.domain + 'step/orderStep?threeSession=' + threeSession + '&next=' + next,
      dataType: 'json',
      success: function (data) {
        if (data.data == 'fail' || data.data == '' || data.data == null) {
          wx.hideLoading();
          return;
        }
        self.globalData.orders = data.data;
        if (isFirst && self.stepOrdersReadyCallback) {
          self.stepOrdersReadyCallback(data)
        } else if (self.stepSecondOrdersReadyCallback) {
          self.stepSecondOrdersReadyCallback(data)
        }
        var length = self.globalData.length;
        length = (length == null || length == undefined) ? length = 0 : length;
        var add = data.data.length;
        length = length + add;
        self.globalData.length = length;
        wx.hideLoading();
        if (next == 0) {
          self.getTodayRun(threeSession);
        }
      },
      fail: function (res) {
        wx.hideLoading();
      },
      complete: function (res) {
        self.globalData.isSearchOrder = false;
      }
    });
  },
  getTodayRun: function (threeSession) {
    var self = this;
    wx.request({
      url: self.globalData.domain + 'step/todayRun?threeSession=' + threeSession,
      dataType: 'json',
      success: function (data) {
        if (data.data == '' || data.data == null) {
          return;
        }
        self.globalData.todayRun = data.data;
        if (self.todayRunReadyCallback) {
          self.todayRunReadyCallback(self.globalData.todayRun)
        }
      },
      fail: function (res) {
        wx.hideLoading();
      }
    })
  },

})